package com.finalterm.payment.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.finalterm.common.result.Result;
import com.finalterm.payment.dto.PaymentExecuteDTO;
import com.finalterm.payment.service.PaymentService;
import com.finalterm.payment.vo.PaymentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 支付控制器
 */
@Slf4j
@RestController
@RequestMapping("api/payment")
public class PaymentController {
    
    @Autowired
    private PaymentService paymentService;
    
    /**
     * 执行支付
     */
    @PostMapping("/execute")
    @SentinelResource(value = "payment-execute", fallback = "executePaymentFallback")
    public Result<PaymentVO> executePayment(@RequestHeader("X-User-Id") Long userId,
                                          @Valid @RequestBody PaymentExecuteDTO executeDTO) {
        PaymentVO paymentVO = paymentService.executePayment(userId, executeDTO);
        return Result.success(paymentVO);
    }
    
    /**
     * 查询支付记录
     */
    @GetMapping("/order/{orderNo}")
    public Result<PaymentVO> getPaymentByOrderNo(@PathVariable String orderNo) {
        PaymentVO paymentVO = paymentService.getPaymentByOrderNo(orderNo);
        return Result.success(paymentVO);
    }
    
    /**
     * 查询用户支付记录
     */
    @GetMapping("/user")
    public Result<List<PaymentVO>> getUserPayments(@RequestHeader("X-User-Id") Long userId) {
        List<PaymentVO> payments = paymentService.getUserPayments(userId);
        return Result.success(payments);
    }
    
    /**
     * 支付回调
     */
    @PostMapping("/callback")
    public Result<Boolean> paymentCallback(@RequestParam String paymentNo,
                                         @RequestParam String thirdPartyTransactionId,
                                         @RequestParam Integer status) {
        boolean result = paymentService.handlePaymentCallback(paymentNo, thirdPartyTransactionId, status);
        return Result.success(result);
    }
    
    /**
     * 支付执行降级方法
     */
    public Result<PaymentVO> executePaymentFallback(Long userId, PaymentExecuteDTO executeDTO, Throwable ex) {
        log.error("支付服务降级，用户ID：{}，订单号：{}，异常：{}", userId, executeDTO.getOrderNo(), ex.getMessage());
        return Result.error("支付服务暂时不可用，请稍后重试");
    }
}
